package com.coocaa.aries.jmeter.service.impl;

import com.coocaa.aries.core.base.mybatis.QueryTemplate;
import com.coocaa.aries.jmeter.biz.impl.ExtTestCaseBizImpl;
import com.coocaa.aries.jmeter.entity.ExtTestCaseInfoEntity;
import com.coocaa.aries.jmeter.enums.ExecStatusEnums;
import com.coocaa.aries.jmeter.service.IInitLoadQueuingTestCaseService;
import com.coocaa.aries.jmeter.service.IRunTimeProcessService;
import com.coocaa.aries.jmeter.thread.ThreadExecMgr;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author bijiahao
 * @description
 * @date 2020/1/6 10:55
 */
@Service
public class InitLoadQueuingTestCaseServiceImpl implements IInitLoadQueuingTestCaseService, InitializingBean {
    @Autowired
    private ExtTestCaseBizImpl extTestCaseBiz;
    @Autowired
    private IRunTimeProcessService runTimeProcessService;

    @Override
    public void afterPropertiesSet() throws Exception {
        handleInitLoadQueuingTestCase();
        LoopThread loopThread = new LoopThread();
        loopThread.start();
    }

    @Override
    public void handleInitLoadQueuingTestCase() {
        QueryTemplate<ExtTestCaseInfoEntity> query = QueryTemplate.getQueryTemplate();
        query.eq("status", ExecStatusEnums.QUEUING.getCode())
                .orderByAsc("created_date")
        ;
        List<ExtTestCaseInfoEntity> list = extTestCaseBiz.getMapper().selectList(query);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (ExtTestCaseInfoEntity entity : list) {
            try {
                ThreadExecMgr.offer(entity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class LoopThread extends Thread {
        @Override
        public void run() {
            while (true) {
                if (!ThreadExecMgr.isExecuing() && !ThreadExecMgr.deque.isEmpty()) {
                    ExtTestCaseInfoEntity entity = ThreadExecMgr.deque.poll();
                    System.out.println("id:" + entity.getId() + "isEx: " + ThreadExecMgr.isExecuing());
                    try {
                        ThreadExecMgr.set(true);
                        runTimeProcessService.exec(entity);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
